<?php

namespace youmbe\phpword\widgets;

use Yii;
use yii\helpers\ArrayHelper;
use PhpOffice\PhpWord\Style\TablePosition;
use yii\base\Arrayable;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\Inflector;
use PhpOffice\PhpWord\Shared\Converter;

/**
 * The GridView widget is used to display data in a grid.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class GridView extends BaseTableView {

    /**
     * @var \PhpOffice\PhpWord\Element\Table
     */
    public $table;

    /**
     * @var \yii\data\DataProviderInterface the data provider for the view. This property is required.
     */
    public $dataProvider;

    /**
     * @var string the default data column class if the class name is not explicitly specified when configuring a data column.
     * Defaults to 'yii\grid\DataColumn'.
     */
    public $dataColumnClass;

    /**
     * @var string the caption of the grid table
     * @see captionOptions
     */
    public $caption;

    /**
     * @var array the HTML attributes for the table header row.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $headerRowOptions = [
        'fontStyle' => [
            'name' => '华文中宋',
            'size' => 12,
            'bold' => true
        ],
    ];

    /**
     * @var array the HTML attributes for the table footer row.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $footerRowOptions = [];

    /**
     * @var array|Closure the HTML attributes for the table body rows. This can be either an array
     * specifying the common HTML attributes for all body rows, or an anonymous function that
     * returns an array of the HTML attributes. The anonymous function will be called once for every
     * data model returned by [[dataProvider]]. It should have the following signature:
     *
     * ```php
     * function ($model, $key, $index, $grid)
     * ```
     *
     * - `$model`: the current data model being rendered
     * - `$key`: the key value associated with the current data model
     * - `$index`: the zero-based index of the data model in the model array returned by [[dataProvider]]
     * - `$grid`: the GridView object
     *
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $rowOptions = [
        'fontStyle' => [
            'size' => 12,
        ],
    ];

    /**
     * @var bool whether to show the header section of the grid table.
     */
    public $showHeader = true;

    /**
     * @var bool whether to show the footer section of the grid table.
     */
    public $showFooter = false;

    /**
     * @var bool whether to place footer after body in DOM if $showFooter is true
     * @since 2.0.14
     */
    public $placeFooterAfterBody = false;

    /**
     * @var bool whether to show the grid view if [[dataProvider]] returns no data.
     */
    public $showOnEmpty = true;

    /**
     * @var array grid column configuration. Each array element represents the configuration
     * for one particular grid column. For example,
     *
     * ```php
     * [
     *     ['class' => SerialColumn::className()],
     *     [
     *         'class' => DataColumn::className(), // this line is optional
     *         'attribute' => 'name',
     *         'format' => 'text',
     *         'label' => 'Name',
     *     ],
     *     ['class' => CheckboxColumn::className()],
     * ]
     * ```
     *
     * If a column is of class [[DataColumn]], the "class" element can be omitted.
     *
     * As a shortcut format, a string may be used to specify the configuration of a data column
     * which only contains [[DataColumn::attribute|attribute]], [[DataColumn::format|format]],
     * and/or [[DataColumn::label|label]] options: `"attribute:format:label"`.
     * For example, the above "name" column can also be specified as: `"name:text:Name"`.
     * Both "format" and "label" are optional. They will take default values if absent.
     *
     * Using the shortcut format the configuration for columns in simple cases would look like this:
     *
     * ```php
     * [
     *     'id',
     *     'amount:currency:Total Amount',
     *     'created_at:datetime',
     * ]
     * ```
     *
     * When using a [[dataProvider]] with active records, you can also display values from related records,
     * e.g. the `name` attribute of the `author` relation:
     *
     * ```php
     * // shortcut syntax
     * 'author.name',
     * // full syntax
     * [
     *     'attribute' => 'author.name',
     *     // ...
     * ]
     * ```
     */
    public $columns = [];

    /**
     * @var string the HTML display when the content of a cell is empty.
     * This property is used to render cells that have no defined content,
     * e.g. empty footer or filter cells.
     *
     * Note that this is not used by the [[DataColumn]] if a data item is `null`. In that case
     * the [[\yii\i18n\Formatter::nullDisplay|nullDisplay]] property of the [[formatter]] will
     * be used to indicate an empty data value.
     */
    public $emptyCell = '&nbsp;';

    /**
     * @var array|null 标签选项
     */
    public $captionOptions;

    /**
     * @var array|null 内容选项
     */
    public $contentOptions;

    /**
     * @var array|string|null 首行样式
     */
    public $firstRowStyle = [
        //'bgColor' => 'ff6600',
        'cellMarginBottom' => 50,
        'cellSpacing' => 0,
    ];

    /**
     * @var array|string|null 单元格样式
     */
    public $cellStyle = [
        'valign' => 'center',
        'borderColor' => 'ff6600',
        'borderSize' => 2,
        'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
    ];

    /**
     * Initializes the grid view.
     * This method will initialize required property values and instantiate [[columns]] objects.
     */
    public function init() {
        parent::init();
        if ($this->dataProvider === null) {
            throw new InvalidConfigException('The "dataProvider" property must be set.');
        }
        $this->initColumns();
    }

    /**
     * Runs the widget.
     */
    public function run() {
        if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) {
            parent::run();
        } else {
            $this->renderEmpty();
        }
    }

    /**
     * Renders the data models for the grid view.
     * @return string the HTML code of table
     */
    public function renderLayout() {
        $this->showHeader && $this->renderTableHeader();
        $this->renderTableBody();
        $this->showFooter && $this->renderTableFooter();
    }

    /**
     * Renders the HTML content indicating that the list view has no data.
     * @return string the rendering result
     * @see emptyText
     */
    public function renderEmpty() {
        if ($this->emptyText === false) {
            return '';
        }
        $this->section->addText($this->emptyText);
    }

    /**
     * Renders the table header.
     * @return string the rendering result.
     */
    public function renderTableHeader() {
        $height = ArrayHelper::getValue($this->headerRowOptions, 'height');
        if ($height) {
            $height = Converter::pointToTwip($height);
        }
        $rowStyle = $this->filterRowStyles($this->headerRowOptions);
        $fontStyle = ArrayHelper::getValue($this->headerRowOptions, 'fontStyle');
        $paragraphStyle = ArrayHelper::getValue($this->headerRowOptions, 'paragraphStyle');
        $cellStyle = ArrayHelper::getValue($this->headerRowOptions, 'cellStyle');

        $options = [];
        if ($fontStyle) {
            $options['fontStyle'] = $fontStyle;
        }
        if ($paragraphStyle) {
            $options['paragraphStyle'] = $paragraphStyle;
        }
        if ($cellStyle) {
            $options['cellStyle'] = $cellStyle;
        }

        $row = $this->layout->addRow($height, $rowStyle);
        $defaultCellWidth = 100 / count($this->columns);
        foreach ($this->columns as $column) {
            $options = $column->headerOptions;
            $fontStyle = $this->mergeStyleArray('fontStyle', $this->headerRowOptions, $options);
            if ($fontStyle) {
                $options['fontStyle'] = $fontStyle;
            }
            $paragraphStyle = $this->mergeStyleArray('paragraphStyle', $this->headerRowOptions, $options);
            if ($paragraphStyle) {
                $options['paragraphStyle'] = $paragraphStyle;
            }
            $cellWidth = ArrayHelper::getValue($column->headerOptions, 'width') ?: $defaultCellWidth;
            if ($cellWidth) {
                $options['width'] = $cellWidth;
            }
            /* @var $column Column */
            $this->renderCell($row, $column->renderHeaderCell(), $options);
        }
    }

    /**
     * Renders the table footer.
     * @return string the rendering result.
     */
    public function renderTableFooter() {
        $height = ArrayHelper::getValue($this->footerRowOptions, 'height');
        if ($height) {
            $height = Converter::pointToTwip($height);
        }
        $rowStyle = $this->filterRowStyles($this->footerRowOptions);
        $fontStyle = ArrayHelper::getValue($this->footerRowOptions, 'fontStyle', $this->fontStyle);
        $paragraphStyle = ArrayHelper::getValue($this->footerRowOptions, 'paragraphStyle', $this->paragraphStyle);
        $row = $this->layout->addRow($height, $rowStyle);
        foreach ($this->columns as $column) {
            /* @var $column Column */
            $row->addCell()->addText($column->renderFooterCell(), $fontStyle, $paragraphStyle);
        }
    }

    /**
     * Renders the table body.
     * @return string the rendering result.
     */
    public function renderTableBody() {
        $models = array_values($this->dataProvider->getModels());
        $height = ArrayHelper::getValue($this->rowOptions, 'height');
        if ($height) {
            $height = Converter::pointToTwip($height);
        }
        $rowStyle = $this->filterRowStyles($this->rowOptions);
        foreach ($models as $index => $model) {
            $this->layout->addRow($height, $rowStyle);
            $this->renderTableRow($model, $index);
        }
    }

    /**
     * Renders a table row with the given data model and key.
     * @param mixed $model the data model to be rendered
     * @param mixed $key the key associated with the data model
     * @param int $index the zero-based index of the data model among the model array returned by [[dataProvider]].
     * @return string the rendering result
     */
    public function renderTableRow($model, $index) {
        /* @var $column Column */
        foreach ($this->columns as $column) {
            $options = $column->contentOptions;
            $fontStyle = $this->mergeStyleArray('fontStyle', $this->rowOptions, $options);
            if ($fontStyle) {
                $options['fontStyle'] = $fontStyle;
            }
            $paragraphStyle = $this->mergeStyleArray('paragraphStyle', $this->rowOptions, $options);
            if ($paragraphStyle) {
                $options['paragraphStyle'] = $paragraphStyle;
            }
            /* @var $column Column */
            $this->renderCell($this->layout, $column->renderDataCell($model, $index), $options);
        }
    }

    /**
     * Creates column objects and initializes them.
     */
    protected function initColumns() {
        if (empty($this->columns)) {
            $this->guessColumns();
        }
        foreach ($this->columns as $i => $column) {
            if (is_string($column)) {
                $column = $this->createDataColumn($column);
            } else {
                $column = Yii::createObject(array_merge([
                    'class' => $this->dataColumnClass ?: DataColumn::className(),
                    'grid' => $this,
                ], $column));
            }
            if (!$column->visible) {
                unset($this->columns[$i]);
                continue;
            }
            $this->columns[$i] = $column;
        }
    }

    /**
     * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
     * @param string $text the column specification string
     * @return DataColumn the column instance
     * @throws InvalidConfigException if the column specification is invalid
     */
    protected function createDataColumn($text) {
        if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
            throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
        }
        return Yii::createObject([
            'class' => $this->dataColumnClass ?: DataColumn::className(),
            'grid' => $this,
            'attribute' => $matches[1],
            'format' => isset($matches[3]) ? $matches[3] : 'text',
            'label' => isset($matches[5]) ? $matches[5] : null,
        ]);
    }

    /**
     * This function tries to guess the columns to show from the given data
     * if [[columns]] are not explicitly specified.
     */
    protected function guessColumns() {
        $models = $this->dataProvider->getModels();
        $model = reset($models);
        if (is_array($model) || is_object($model)) {
            foreach ($model as $name => $value) {
                if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
                    $this->columns[] = (string) $name;
                }
            }
        }
    }

}
